<?php
// +----------------------------------------------------------------------
// | 中联致远服务端框架
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.zhongliansoft.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: tony <tanyu@zhongliansoft.com>
// +----------------------------------------------------------------------

namespace app\common\model;
use think\Validate;
use think\model\concern\SoftDelete;
use app\common\model\User as UserModel;
use think\facade\Log;

class AssistantUserRel extends Common
{
    //时间自动存储
    protected $autoWriteTimestamp = true;
    protected $createTime = 'ctime';
    protected $updateTime = 'utime';
    //软删除位
    protected $deleteTime = 'isdel';

    protected $rule = [
        'assistantUserMobile'   => 'require',
        'userMobile'   => 'require',
    ];
    protected $msg = [
        'assistantUserMobile'   => '请选择助手',
        'userMobile'   => '管理员数据异常请重试',
    ];

    /**
     * @param $post
     *
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function tableData($post)
    {
        if(isset($post['limit'])){
            $limit = $post['limit'];
        }else{
            $limit = config('paginate.list_rows');
        }

        $tableWhere = $this->tableWhere($post);
        $list = $this->alias('r')
            ->join('user u', 'r.assistantUserMobile = u.mobile')
            ->field($tableWhere['field'])
            ->where($tableWhere['where'])
            ->order($tableWhere['order'])
            ->paginate($limit);
        $data = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型

        $re['code'] = 0;
        $re['msg'] = '';
        $re['count'] = $list->total();
        $re['data'] = $data;

        return $re;
    }

    /**
     *  添加品牌
     * User:tony
     * @param $data
     * @return array
     */
    public function addData($data)
    {
        $result = [
            'status' => true,
            'msg' => '保存成功',
            'data'=> [],
        ];
        $validate = new Validate($this->rule,$this->msg);
        if (!$validate->check($data)) {
            $result['status'] = false;
            $result['msg'] = $validate->getError();
        } else {
            // 判断是否一个人被多人添加为助手
            $info = $this->field('truename')
                ->alias('r')
                ->join('user u', 'u.mobile = r.userMobile')
                ->where(['assistantUserMobile'=>$data['assistantUserMobile']])->find();
            
            if($info){
                $result['status'] = false;
                $result['msg'] = '该用户已是' . $info['truename'] . '的助手';   
            } else { 
                // 判断委托人是否被其他人委托
                $infoSelf = $this->field('truename')
                    ->alias('r')
                    ->join('user u', 'u.mobile = r.userMobile')
                    ->where(['assistantUserMobile'=>$data['userMobile']])->find();
            
                if($infoSelf){
                    $result['status'] = false;
                    $result['msg'] = '管理员已是' . $infoSelf['truename'] . '的助手，不能嵌套添加助手';   
                } else { 
                    // 如果已经有助手了也不能被添加为助手
                    $infoExist = $this->where(['userMobile'=>$data['assistantUserMobile']])->find();
                    if($infoExist){
                        $result['status'] = false;
                        $result['msg'] = '当前用户已经有助手了！';   
                    } else { 
                        // $userModel = new UserModel();
                        // $userDeptId = $userModel->field('deptId')->where(['mobile' => $data['userMobile']])->find()['deptId'];
                        // $assistantUserDeptId = $userModel->field('deptId')->where(['mobile' => $data['assistantUserMobile']])->find()['deptId'];

                        // if($userDeptId != $assistantUserDeptId){
                        //     $result['status'] = false;
                        //     $result['msg'] = '辅导员与助手不属于同一部/院！';   
                        // } else { 
                            $info['assistantUserMobile'] = $data['assistantUserMobile'];
                            $info['userMobile'] = $data['userMobile']; 

                            if (!$this->allowField(true)->save($info))
                            {
                                $result['status'] = false;
                                $result['msg'] = '保存失败';
                            }
                        // }
                    }
                }
            }
        }
        $result['token'] = \think\facade\Request::token('__ZlServer_Token__', 'sha1');
        return $result;
    }
 
    //where搜索条件
    protected function tableWhere($post)
    {
        $where = [];
        
        if(isset($post['mobile']) && $post['mobile'] != ""){
            $where[] = ['userMobile', 'eq', $post['mobile']];
        }

        $result['where'] = $where;
        $result['field'] = "*";
        $result['order'] = 'assistantUserMobile';
        return $result;
    }

    /**
     * @param $list
     *
     * @return mixed
     */
    protected function tableFormat($list)
    {
        // $userModel = new UserModel();
        // foreach($list as &$val){ 
        //     $val['truename'] = $userModel->where(['mobile'=>$val['mobile']])->find()['truename'];
        // }
        return $list;
    }
}